package com.example.carbonlife.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.carbonlife.common.Constants;
import com.example.carbonlife.entity.User;
import com.example.carbonlife.exception.ServiceException;
import com.example.carbonlife.mapper.UserMapper;
import com.example.carbonlife.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    //居民用户数据层
    @Resource
    private UserMapper userMapper;


    /**
     * 根据openId查询用户信息
     * @param openId
     * @return User
     */
    @Override
    public User getUserInfo(String openId) {
        return userMapper.selectOne(new QueryWrapper<User>().eq("open_id", openId));
    }

    /**
     * 根据时间更新每周挑战
     * @param currentTime
     * @param id
     */
    @Override
    public boolean updateDate(String currentTime, Integer id) {
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("id", id));
        String loginTime = user.getLoginDate();
        long betweenDay = DateUtil.betweenDay(DateUtil.parse(currentTime), DateUtil.parse(loginTime), true);
        if(betweenDay >= 7) {
            user.setLoginDate(currentTime);
            this.saveOrUpdate(user);
            return true;
        }
        return false;
    }

    /**
     * 查询用户积分
     * @param userId
     */
    @Override
    public User selectUserInfo(Integer userId) {
        return userMapper.selectOne(new QueryWrapper<User>().eq("id", userId));
    }

    /**
     * 查询所有用户积分
     */
    @Override
    public List<User> selectAllUsers() {
        List<User> users = userMapper.selectList(new QueryWrapper<User>().orderByDesc("points"));
        List<User> filteredUser = users.stream().map(user -> new User(user.getName(),user.getPoints(), user.getAvatar(), null))
                .collect(Collectors.toList());
        return filteredUser;
    }

    /**
     * 查询用户积分排名
     * @param userId
     */
    @Override
    public int getUserRank(Integer userId) {
        int rank = 0;
        List<User> users = userMapper.selectList(new QueryWrapper<User>().orderByDesc("points"));
        for (int i = 0; i < users.size(); i ++ ){
            User user = users.get(i);
            if(user.getId() == userId) rank = i + 1;
        }
        return rank;
    }

    /**
     * 查询用户积分
     * @param userId
     */
    @Override
    public int queryUserPoints(Integer userId) {
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("id", userId));
        return user.getPoints();
    }



}
